<template>
  <div class="box">
    <div class="left">
      <!-- ------------------------------------------------ -->
      <div class="bigTitle">
        <div></div>
        <div>答题卡</div>
      </div>
      <div v-for="item in testQuestionsInFo" class="bigQuestionItem">

        <div class="bigTopInFo">
          <span>{{ item.name }}</span>
          <span>(共</span>
          <span>{{ item.xiao.length }}题</span>

          <span>)</span>
        </div>
        <div class="bigBottomInFo">
          <div v-for="xiao in item.xiao" :class="{bigBottomXiaoItemValue:xiao.itemInfo.value!=null}"
               class="bigBottomXiaoItem">
            <a
              href="#"
              @click="
                () => {
                  scrollToElement(item.sort + xiao.sort);
                  return false;
                }
              "
            >{{ xiao.sort }}</a
            >
          </div>
        </div>
        <div class="line"></div>
      </div>
      <!-- ------------------------------------------------ -->
    </div>
    <div
      class="center"
    >
      <div
        v-for="(item, indexBig) in testQuestionsInFo"
        ref="page-cont"
        class="topicBox"
      >
        <div class="topicBottom">
          <div class="topicBottomContent">
            <div>
              <div
                v-for="(xiao, index) in item.xiao"
                :id="item.sort + xiao.sort"
                class="xiaoItem"
              >
                <div class="pdf-split-page pdf-group-item answerSheet"
                     style="margin: 0 auto;padding: 20px 0;box-sizing: border-box">


                  <div v-if="index==0" class="topicTop">
                    <div class="bigTopInFo">
                      <span>{{ item.name }}</span>
                      <span>(共</span>
                      <span>{{ item.xiao.length }}题</span>
                      <span>)</span>
                    </div>
                  </div>
                  <div class="xiaoInFo">
                  <span>
                    {{ xiao.sort }}.{{ xiao.itemInfo.questionTypes }}
                  </span>
                    <div style="display: flex; align-items: center"></div>
                  </div>
                  <div class="xiaoContent">
                    <!-- 单选 -->
                    <template v-if="xiao.itemInfo.questionTypes == '单选题'">
                      <div
                        class="xiaoStem"
                        v-html="setContent(gogo(xiao.itemInfo.testItemContent))"
                      ></div>
                      <div class="xiaoOption">
                        <div
                          v-for="option in xiao.itemInfo.answerList"
                          class="xiaoOptionItem"
                        >
                          <el-radio
                            v-model="xiao.itemInfo.value"
                            :label="option.identifier"
                          >
                            {{ '' }}
                            <!--                            {{ option.identifier }}-->
                          </el-radio
                          >
                          <span style="padding-left: 20px">{{
                              option.identifier
                            }}</span>
                          <div class="optionInput">
                            <div v-html="option.answerContent"></div>
                          </div>
                        </div>
                      </div>
                      <div class="analysisBox">
                        <div class="analyTitle">解析详情</div>
                        <div
                          class="anlysisHtml"
                          v-html="setContent(gogo(xiao.itemInfo.analysis))"
                        ></div>
                      </div>
                    </template>
                    <!-- 单选 -->
                    <!-- 多选 -->
                    <template v-if="xiao.itemInfo.questionTypes == '多选题'">
                      <div
                        class="xiaoStem"
                        v-html="setContent(gogo(xiao.itemInfo.testItemContent))"
                      ></div>
                      <div class="xiaoOption">

                        <div
                          v-for="option in xiao.itemInfo.answerList"
                          class="xiaoOptionItem"
                        >
                          <el-checkbox
                            :label="option.identifier"
                            @change="getManyChange(xiao.itemInfo,option.identifier)"
                          >
                            {{ '' }}
                          </el-checkbox
                          >
                          <span style="padding-left: 20px">{{
                              option.identifier
                            }}</span>
                          <div class="optionInput">
                            <div v-html="option.answerContent"></div>
                          </div>
                        </div>
                      </div>
                      <div class="analysisBox" style="display: none">
                        <div class="analyTitle">解析详情</div>
                        <div
                          class="anlysisHtml"
                          v-html="setContent(gogo(xiao.itemInfo.analysis))"
                        ></div>
                      </div>
                    </template>
                    <!-- 多选 -->
                    <!-- 判断 -->
                    <template v-if="xiao.itemInfo.questionTypes == '判断题'">
                      <div
                        class="xiaoStem"
                        v-html="setContent(gogo(xiao.itemInfo.testItemContent))"
                      ></div>
                      <div class="xiaoOption" style="margin: 15px 0">
                        <el-radio label="1">正确</el-radio>
                        <el-radio label="2">错误</el-radio>
                      </div>
                      <div class="analysisBox" style="display: none">
                        <div class="analyTitle">解析详情</div>
                        <div
                          class="anlysisHtml"
                          v-html="setContent(gogo(xiao.itemInfo.analysis))"
                        ></div>
                      </div>
                    </template>
                    <!-- 判断 -->
                    <!-- 应用 -->
                    <template v-if="xiao.itemInfo.questionTypes == '应用题'">
                      <div
                        class="xiaoStem"
                        v-html="setContent(gogo(xiao.itemInfo.testItemContent))"
                      ></div>
                      <div class="analysisBox" style="display: none">
                        <div class="analyTitle">解析详情</div>
                        <div
                          class="anlysisHtml"
                          v-html="setContent(gogo(xiao.itemInfo.analysis))"
                        ></div>
                      </div>
                      <tinymce v-model="xiao.itemInfo.value"/>
                    </template>
                    <!-- 应用 -->
                    <!-- 填空 -->
                    <template v-if="xiao.itemInfo.questionTypes == '填空题'">
                      <div
                        class="xiaoStem"
                        v-html="setContent(gogo(xiao.itemInfo.testItemContent))"
                      ></div>
                      <div class="xiaoOption">
                        <div
                          v-for="option in xiao.itemInfo.answerList"
                          class="xiaoOptionItem"
                        >
                          <div class="optionInput">
                            <div v-html="option.answerContent"></div>
                          </div>
                        </div>
                      </div>
                      <div class="analysisBox" style="display: none">
                        <div class="analyTitle">解析详情</div>
                        <div
                          class="anlysisHtml"
                          v-html="setContent(gogo(xiao.itemInfo.analysis))"
                        ></div>
                      </div>
                    </template>
                    <!-- 填空 -->

                  </div>


                </div>


              </div>

            </div>
          </div>
        </div>
      </div>
    </div>
    <div :style="{ display: id != '' ? 'none' : 'block' }" class="right">
      <div>
        <div class="countdown">
          <div>剩余时间</div>
          <span>{{ hours }}</span
          ><span>:</span><span>{{ minutes }}</span
        ><span>:</span><span>{{ remainingSeconds }}</span>
        </div>
      </div>
      <el-button class="subExams" type="primary" @click="subMit">提交试卷</el-button>
    </div>

    <el-dialog
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
      :visible.sync="dialogVisible"
      title="提示"
      width="30%">
      <span>{{info.remark}}</span>
      <span slot="footer" class="dialog-footer">
    <el-button :disabled="compulsoryReadingTime>0" type="primary" @click="dialogVisible = false">已知晓 <span
      v-if="compulsoryReadingTime>0">({{ compulsoryReadingTime }})</span></el-button>
  </span>
    </el-dialog>


  </div>
</template>
<script>
import {getSummary} from "@/api/examPaperLibrary";
import tinymce from "@/components/tinymce/index.vue";
import {submitExamination} from "@/api/examination";
import {mapGetters} from "vuex";

export default {
  components: {tinymce},
  props: {
    id: {
      require: false,
      default: "",
    },
  },

  data() {
    return {
      testPaperData: {},
      form: {
        bigProblem: 0, //大题数量
        questions: 0, //小题数量
        totalPoints: 0, //总分
        testPaperClassificationId: null, //试卷分类id
        examinationPaperSummaryName: "",
        examinationPaperDetailsList: [],
      },
      testQuestionsInFo: [],
      hours: "00", //时
      minutes: "00", //分
      remainingSeconds: "00", //秒
      intervalId: null, //定时器
      boxHeight: null,
      isPrinting: true,
      info: {},
      dialogVisible: true,//考试说明弹窗
      compulsoryReadingTime: 0
    };
  },
  computed: {
    ...mapGetters(["userId"]),
  },
  mounted() {
    this.info = JSON.parse(localStorage.getItem('examHallData'));


    this.getTestPaperDetail(this.info.id);

    this.startCountdown(3599);
    document.addEventListener('visibilitychange', this.hidePage);
    //判断是否强制阅读
    this.compulTime()


  },
  updated() {
    //判断是否初始配置，若无则配置。
    if (!this.mathJax.isMathjaxConfig.bool) {
      this.mathJax.initMathjaxConfig();
    }
    this.$nextTick((_) => {
      //传入组件id，让组件被MathJax渲染
      this.mathJax.MathQueue("questionList-page");
    });
  },
  methods: {

    //获取试卷详情(回显)
    getTestPaperDetail(val) {
      getSummary(val).then((res) => {
        if (res.code == 200) {
          let obj = JSON.parse(JSON.stringify(res.data));
          delete obj.examinationPaperDetailsList;
          console.log(obj);
          this.form = obj;

          const transformedData = res.data.examinationPaperDetailsList.reduce(
            (accumulator, currentValue) => {
              // 查找是否已有相应的题号（name1）在累积器中
              const existingItem = accumulator.find(
                (item) => item.name === currentValue.bigProblem
              );
              if (existingItem) {
                // 如果找到，则向xiao数组中添加当前小题对象
                currentValue.itemBank['value'] = null
                let xiaoObj = {
                  xName: currentValue.questions,
                  itemBankId: currentValue.itemBankId,
                  itemInfo: currentValue.itemBank,
                  fenzhi: currentValue.score,
                  fenzhiIsNull: false,
                  sort: currentValue.questions.split(".")[0],
                };
                existingItem.xiao.push(xiaoObj);
              } else {
                // 如果没有找到，则创建一个新对象，并初始化xiao数组
                currentValue.itemBank['value'] = null
                let digQu = {
                  name: currentValue.bigProblem,
                  sort: currentValue.reserve1,
                  fenzhi: 0,
                  xiao: [
                    {
                      xName: currentValue.questions,
                      itemBankId: currentValue.itemBankId,
                      itemInfo: currentValue.itemBank,
                      fenzhi: currentValue.score,
                      fenzhiIsNull: false,
                      sort: currentValue.questions.split(".")[0],
                    },
                  ],
                };

                accumulator.push(digQu);
              }

              // 返回累积器以便进行下一次迭代
              return accumulator;
            },
            []
          ); // 初始值为空数组
          console.log(transformedData);
          this.$set(this, "testQuestionsInFo", transformedData);
        }
      });
    },

    //倒计时
    startCountdown(seconds) {
      function bu(val) {
        if (val < 10) {
          return `0${val}`;
        } else {
          return val;
        }
      }

      this.intervalId = setInterval(() => {
        this.hours = bu(Math.floor(seconds / 3600));
        this.minutes = bu(Math.floor((seconds % 3600) / 60));
        this.remainingSeconds = bu(seconds % 60);

        if (seconds <= 0) {
          clearInterval(this.intervalId);
          countdownElement.textContent = "倒计时结束!";
        } else {
          seconds--;
        }
      }, 1000);
    },
    //每个大题的总分
    setFenzhi(n) {
      let amount = 0;
      n.xiao.forEach((ele) => {
        amount += Number(ele.fenzhi);
      });
      return amount;
    },
    scrollToElement(elementId) {
      var element = document.getElementById(elementId);
      if (element) {
        element.scrollIntoView({behavior: "smooth"}); // 平滑滚动
      }
    },

    //img去除\\
    setContent(val) {
      if (!val) return;

      if (val.includes('\\\\"')) {
        let abc = val.replaceAll('\\\\"', "");
        return abc;
      } else {
        let abc = val.replaceAll('\\"', "");
        return abc;
      }
    },

    gogo(val) {
      // console.log(val);
      if (val == "" || val == null) return;
      let item = JSON.parse(JSON.stringify(val));
      let ord = /begin{array}([\s\S]*?)\\end{array}/g; // 定义正则表达式，用于匹配以 [\begin{array} 开头的字符串

      let arr = item.match(ord); // 使用 match 方法获取所有匹配项
      // console.log(arr, "arr");
      if (arr == null || arr.length == 0) return val;

      let deleP = (P) => {
        let newP = P.split("<p>");
        let a = newP.join(" ");
        let b = a.split("</p>");
        let c = b.join(" ");
        // console.log(c, "newp");
        return c;
      };

      let abc = null;
      arr.forEach((ele) => {
        abc = val.split(ele);
        abc = abc.join(deleP(ele));
      });
      return abc;
      console.log(abc, "拼接完成");
    },
    //多选题选中
    getManyChange(arr, val) {
      console.log(arr, val)
      if (Array.isArray(arr.value)) {
        console.log("变量是数组");
        if (arr.value.includes(val)) {
          const index = arr.value.indexOf(val); // 找到val在数组中的索引
          if (index !== -1) { // 确保找到了val
            arr.value.splice(index, 1); // 从数组中删除val
          }
        } else {
          arr.value.push(val); // 如果val不在数组中，将其添加到数组开头
        }
      } else {
        console.log("变量不是数组");
        arr.value = [val];
      }
    },
    //提交试卷
    subMit(type=true) {
      console.log(this.testQuestionsInFo)
      let xiaoList = []
      this.testQuestionsInFo.forEach(ele => {
        ele.xiao.forEach((ele2, index2) => {
          xiaoList.push(ele2.itemInfo)
        })
      })
      let studentTestAnswerList = xiaoList.map(ele => {
        let arr = ele.value
        if (Array.isArray(arr)) {
          arr = arr.join(',')
        }

        return {
          answer: arr,
          itemBankId: ele.itemBankId
        }
      })
      console.log(this.info)
      let form = {
        // studentTestAnswerList:JSON.stringify(studentTestAnswerList),
        studentTestAnswerList: studentTestAnswerList,
        examinationId: this.info.examinationId,
        examinationAndUserId: this.info.userAndId
      }
      console.log(form)


      submitExamination(form).then(ele => {
        if (ele.code == 200) {
          this.$message({
            message: '提交成功',
            type: 'success'
          });
          if(type){
            this.$router.back(1)
          }
        }
      })
    },
    //隐藏当前页面的操作
    hidePage() {

      if (document.visibilityState === 'visible') {
        console.log('Tab is now visible');
        // 用户切换回标签页时执行的代码
        this.dialogVisible=true
      } else if (document.visibilityState === 'hidden') {
        console.log('Tab is now hidden');
        // 用户切换到其他标签页时执行的代码
      }
    },
    //判断强制阅读多长时间
    compulTime() {
      if (this.info.compulsoryReading == 0) {
        return this.compulsoryReadingTime == 0
      }
      this.compulsoryReadingTime = this.info.compulsoryReadingTime


      let int = setInterval(() => {


        console.log(this.compulsoryReadingTime)
        this.compulsoryReadingTime--
        if (this.compulsoryReadingTime <= 0) {
          clearInterval(int)
        }
      }, 1000)

    }


  },

};
</script>
<style lang="scss" scoped>
.bigTitle {
  font-size: 16px;
  display: flex;
  align-items: center;
  margin-top: 15px;
  margin-left: 15px;
  font-weight: bold;
  font-size: 18px;

  > div:nth-of-type(1) {
    width: 8px;
    height: 20px;
    background-color: rgba(0, 60, 255, 0.79);
    margin-right: 10px;
  }
}


.box {
  display: flex;
  padding: 0 80px;
  height: 100%;
  background-color: #f1f3f8;
  position: relative;

  > .left {
    width: 300px;
    background-color: white;
    height: calc(100% - 30px);
    position: absolute;
    top: 15px;
  }

  > .center {
    flex: 1;
    background-color: white;
    margin: 15px 0 0 315px;
    overflow: auto;
    min-width: 600px;
  }

  > .right {
    width: 200px;
    margin-top: 15px;
    margin-left: 15px;
    position: relative;

    > div:nth-of-type(1) {
      height: 200px;
      background-color: white;
      display: flex;
      flex-direction: column;
      align-items: center;

      .countdown {
        text-align: center;

        > div {
          margin: 10px 0;
          font-size: 12px;
        }

        > span {
          color: red;
          font-size: 16px;
          font-weight: bold;
        }
      }
    }

    .subExams {
      width: 190px;
      height: 50px;
      margin: 0 5px;
      position: absolute;
      bottom: 15px;
    }
  }
}

.bigQuestionItem {
  width: 100%;
  min-height: 50px;
  padding: 10px 15px;

  .bigTopInFo {
    display: flex;
    align-items: center;
    font-size: 14px;
  }

  .bigBottomInFo {
    padding: 15px 0;
    display: flex;
    flex-wrap: wrap;

    .bigBottomXiaoItem {

      height: 25px;
      width: 25px;
      line-height: 25px;
      text-align: center;
      border: 1px #eee solid;
      margin-right: 10px;
      margin-bottom: 10px;
    }

    .bigBottomXiaoItemValue {
      background-color: #3a63f3;
      color: white;
    }
  }
}

.line {
  height: 1px;
  background-color: #eee;
}

/**
题干
*/

.topicBox {
  .topicTop {
    height: 60px;
    background-color: #f7f8fa;
    padding: 16px 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    box-sizing: border-box;

    .el-input {
      width: 40%;
    }

    > div:nth-of-type(2) {
      display: flex;
      align-items: center;
      color: #656577;

      i {
        margin-left: 15px;
        color: #656577;
      }

      > span {
        margin-left: 15px;
      }
    }
  }

  .topicBottom {
    .topicBottomContent {
      .errBottom {
        text-align: center;
        color: #656577;
        line-height: 150px;
        font-size: 12px;
      }
    }

    .topicBottomFooter {
      height: 70px;
      display: flex;
      align-items: center;
      margin: 0 15px;
    }
  }
}

.xiaoItem {
  padding: 0 15px;

  .xiaoInFo {
    display: flex;
    align-items: center;
    justify-content: space-between;

    > div {
      display: flex;
      align-items: center;

      i {
        margin-left: 5px;
        color: #656577;
      }

      > .el-form {
        .el-form-item {
          margin-bottom: 0;
        }
      }
    }
  }

  .xiaoContent {
    min-height: 400px;

    .xiaoStem {
      padding: 10px;
    }

    .xiaoOption {
      .el-radio-group {
        width: 100%;
      }

      .xiaoOptionItem {
        display: flex;
        align-items: center;

        .optionInput {
          width: 100%;
          flex: 1;
          margin: 5px;

          > div {
            padding: 0 10px;
          }
        }

        .optionInputBtn {
          opacity: 0;
          height: 100%;

          i {
            color: #656577;
          }
        }
      }

      .xiaoOptionItem:hover {
        .optionInputBtn {
          height: 100%;
          opacity: 1;

          i {
            color: #656577;
          }
        }
      }
    }

    .analysisBox {
      display: none;

      .analyTitle {
        font-size: 14px;
        margin: 10px 0;
      }

      .anlysisHtml {
        padding: 10px;
      }
    }
  }
}

#messageBox {
  max-height: 70vh;
  overflow: auto;
}

//答题卡
.answerSheet {
  box-sizing: border-box;
}


.labelBox {
  padding: 0 10px;

  .labelItem {
    height: 40px;
    margin-bottom: 10px;
    line-height: 40px;
    display: flex;

    > span {
      min-width: 80px;
    }

    .right {
      flex: 1;
      border: 1px solid red;
    }
  }
}

//单选题
.el-radio {
  margin-right: 0;
}
</style>
